#ifndef CHESSBOARDWIDGET_H
#define CHESSBOARDWIDGET_H

#include <QWidget>
#include <QPainter>
#include <QMouseEvent>
#include <QTimer>
#include <QStack>
#include <QSoundEffect> 


class ChessBoardWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ChessBoardWidget(QWidget* parent = nullptr);
    ~ChessBoardWidget();

    // 游戏控制方法
    void initGame();
    void restartGame();
    bool regretMove();
    void setAIMode(bool enabled);

    // 获取游戏状态
    bool isGameOver() const { return m_gameOver; }
    bool isBlackTurn() const { return m_isBlackTurn; }
    int getGameTime() const { return m_gameTime; }

signals:
    void gameStateChanged(bool isBlackTurn);
    void gameOver(int winner);  // 1: 黑棋胜, 2: 白棋胜
    void gameTimeUpdated(int seconds);

protected:
    void paintEvent(QPaintEvent* event) override;
    void mouseMoveEvent(QMouseEvent* event) override;
    void mousePressEvent(QMouseEvent* event) override;
    void resizeEvent(QResizeEvent* event) override;
    void leaveEvent(QEvent* event) override;

private:
    // 常量定义
    static const int BOARD_SIZE = 15;
    static const int CELL_MARGIN = 20;

    //音效设备
    QSoundEffect* m_soundEffect;



    // 游戏状态
    bool m_isBlackTurn;
    bool m_gameOver;
    bool m_showHover;
    int m_gameTime;
    int m_lastMoveRow;
    int m_lastMoveCol;

    // 棋盘数据
    int m_board[BOARD_SIZE][BOARD_SIZE];
    QPoint m_hoverPos;

    // 布局计算
    int m_cellSize;
    QPoint m_boardTopLeft;

    // 控件
    QTimer* m_timer;

    // 历史记录（用于悔棋）
    QStack<QPoint> m_moveHistory;



    // 私有方法
    void calculateBoardSize();
    QPoint windowToBoard(const QPoint& windowPos);
    bool placePiece(int row, int col);
    bool checkWin(int row, int col);
    bool checkFiveInLine(int row, int col, int dr, int dc);
    void switchPlayer();

    // 绘制方法
    void drawBoard(QPainter& painter);
    void drawPieces(QPainter& painter);
    void drawLastMoveMarker(QPainter& painter);
    void drawHoverPiece(QPainter& painter);

private slots:
    void updateTimer();
};

#endif

